<template>
  <!-- 新增部门的弹层 -->
  <el-dialog :title="formData.id?'编辑部门':'新增部门'" :visible="iSbool" :destroy-on-close="true" @close="btnout">
    <!-- 表单组件  el-form   label-width设置label的宽度   -->
    <!-- 匿名插槽 -->
    <el-form ref="addForm" label-width="120px" :model="formData" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="formData.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="formData.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="formData.manager" style="width:80%" placeholder="请选择" @blur="checkManager">
          <el-option v-for="user in employeelist" :key="user.id" :value="user.username" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="formData.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <!-- el-dialog有专门放置底部操作栏的 插槽  具名插槽 -->
    <el-row slot="footer" type="flex" justify="center">
      <!-- 列被分为24 -->
      <el-col :span="6">
        <el-button type="primary" size="small" @click="btnOK">确定</el-button>
        <el-button size="small" @click="btnout">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { getEmployeeSimple } from '@/api/employee'
import { getDepartment, addDepartmentAPI, getDepartDetailAPI, editDepartmentAPI } from '@/api/company'
export default {
  props: {
    iSbool: {
      type: Boolean,
      // 默认值,如果不传就使用默认值
      default: false
    },
    treeNode: {
      type: Object,
      required: true
    }
  },
  data() {
    const checkRepeatName = async(rule, val, callback) => {
      const { depts } = await getDepartment()
      console.log('接收', this.formData.id)
      let isRepeat
      if (this.formData.id) {
        // 编辑
        isRepeat = depts.filter(item => item.pid === this.treeNode.pid).some(item => item.name === val && item.id !== this.treeNode.id)
        console.log('触发编辑')
      } else {
        // 新增
        isRepeat = depts.filter(item => item.pid === this.treeNode.id || item.id === this.treeNode.id).some(item => item.name === val)
        console.log(49, isRepeat)
        console.log('触发新增')
      }

      if (isRepeat) {
        callback(new Error('同一父部门下名字必须唯一'))
      } else {
        callback()
      }
    }
    const checkRepeatCode = async(rule, val, callback) => {
      const { depts } = await getDepartment()
      // some() 方法会依次执行数组的每个元素：
      // 如果有一个元素满足条件，则表达式返回true , 剩余的元素不会再执行检测。
      // 如果没有满足条件的元素，则返回false。
      let isRepeat
      if (this.formData.id) {
        // 编辑
        isRepeat = depts.some(item => item.code === val && item.id !== this.formData.id)
      } else {
        // 新增
        isRepeat = depts.some(item => item.code === val)
      }

      isRepeat ? callback(new Error('编码必须唯一')) : callback()
    }
    return {
      // 员工名字列表
      employeelist: [],
      // 表单需要的数据
      formData: {
        code: '',
        introduce: '',
        manager: '',
        name: '',
        pid: ''
      },
      // 表单校验规则
      rules: {
        name:
         [
           { required: true, message: '部门名称不能为空', trigger: 'blur' },
           { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
           { validator: checkRepeatName, trigger: 'blur' }
         ],
        code:
         [
           { required: true, message: '部门编码不能为空', trigger: 'blur' },
           { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' },
           { validator: checkRepeatCode, trigger: 'blur' }
         ],
        manager:
         [
           { required: true, message: '部门负责人不能为空', trigger: 'blur' }
         ],
        introduce:
         [
           { required: true, message: '部门介绍不能为空', trigger: 'blur' },
           { trigger: 'blur', min: 1, max: 300, message: '部门介绍要求1-50个字符' }
         ]
      }
    }
  },
  async created() {
    this.employeelist = await getEmployeeSimple()
    console.log(this.employeelist)
  },
  methods: {
    checkManager() {
      setTimeout(() => {
        this.$refs.addForm.validateField('manager')
      }, 100)
    },
    // 点击确定按钮
    async btnOK() {
      // validate	对整个表单进行校验的方法，参数为一个回调函数。该回调函数会在校验结束后被调用，
      // 并传入两个参数：是否校验成功和未通过校验的字段。若不传入回调函数，则会返回一个 promise
      await this.$refs.addForm.validate()
      if (this.formData.id) {
        // 如果有id就是编辑
        await editDepartmentAPI(
          this.formData
        )
        this.$message.success('编辑成功')
      } else {
        // 如果没有就是新增
        // 调用接口函数,添加部门
        await addDepartmentAPI({
          ...this.formData,
          pid: this.treeNode.id
        })
      }
      this.$message.success('操作成功')
      // 不能直接修改,否则报错
      // this.iSbool = false
      this.$emit('closeDialog')
      this.$emit('addDepartment')
    },
    // 点击取消按钮
    btnout() {
      // 因为点击编辑按钮后,id会被保存下来,导致了再次点击新增时候,title还是显示编辑部门
      // 为了避免点击新增按钮时候id残留,所以这里重置了数据
      this.formData = {
        code: '',
        introduce: '',
        manager: '',
        name: '',
        pid: ''
      }
      // 对该表单项进行重置，将其值重置为初始值并移除校验结果
      this.$refs.addForm.resetFields()
      this.$emit('closeDialog')
    },
    // 点击编辑按钮后数据回显
    async getDepartment(id) {
      this.formData = await getDepartDetailAPI(id)
    }
  }
}
</script>

<style>

</style>
